namespace SimpleWebServices.Net
{
    using System;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Xml;
    using System.Xml.XPath;

    public sealed class XmlResponse : Response
    {
        private IXPathNavigable _xml;

        public XmlResponse(HttpWebResponse response)
            : base(response.StatusCode, response.ResponseUri, response.Headers, response.Cookies)
        {
            XmlDocument document = null;
            using (Stream stream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    using (XmlTextReader xml = new XmlTextReader(reader))
                    {
                        xml.XmlResolver = null;
                        document = new XmlDocument();
                        document.XmlResolver = null;
                        document.Load(xml);
                    }
                }
            }

            this.Xml = document;
        }

        public IXPathNavigable Xml
        {
            get
            {
                return this._xml;
            }

            private set
            {
                if (null == value)
                {
                    throw new ArgumentNullException("value");
                }

                this._xml = value;
            }
        }

        public static XmlResponse New(HttpRequestDefinition definition, IHttpContent content)
        {
            XmlResponse result = null;

            using (HttpWebResponse response = Response.Http(definition, content) as HttpWebResponse)
            {
                result = new XmlResponse(response);
            }

            return result;
        }

        public override string ToString()
        {
            StringBuilder buffer = new StringBuilder();
            buffer.Append(base.ToString());
            buffer.Append(Environment.NewLine);
            buffer.Append(this.Xml.CreateNavigator().OuterXml);

            return buffer.ToString();
        }
    }
}